<template>
  <BasicModal v-bind="$attrs" :showFooter="true" @register="registerModal" @ok="handleSubmit" width="40%">
    <template #title>
      <Icon icon="ant-design:safety-outlined" class="pr-1 m-1" />
      <span>{{ getTitle }}</span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup name="ViewsTbRoleForm">
  import { ref, computed } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { saveRole } from '/@/api/tb/role';
  import type { Role } from '/@/api/tb/role';

  const emit = defineEmits(['success', 'register']);

  const { showMessage } = useMessage();
  const record = ref<Partial<Role>>({});

  const getTitle = computed(() => (record.value.roleId ? '编辑角色' : '新增角色'));

  const inputFormSchemas: FormSchema[] = [
    {
      label: '角色名称',
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        placeholder: '请输入角色名称',
      },
      required: true,
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true });
    record.value = { ...data };
    await resetFields();

    if (data) {
      setFieldsValue({
        name: data.name,
      });
    }

    setModalProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const formData = await validate();
      setModalProps({ confirmLoading: true });

      // 提取真正的 roleId 字符串
      const roleIdStr = record.value?.roleId?.id || record.value?.id?.id;
      const isEdit = Boolean(roleIdStr);

      const payload: Role = {
        name: formData.name,
        menus: record.value.menus || [],
        roleId:
          isEdit && roleIdStr
            ? {
                id: roleIdStr,
                entityType: 'ROLE',
              }
            : null,
      };

      const result = await saveRole(payload);

      showMessage(`${isEdit ? '编辑' : '新增'}角色成功！`);
      setTimeout(closeModal);
      emit('success', result);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage('表单验证失败', 'error');
      } else {
        const errorMessage = error?.message || error?.data?.message || '未知错误';
        showMessage(`保存角色失败: ${errorMessage}`, 'error');
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
